package com.smartsofa.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.adapter.NewsListAdapter;
import com.smartsofa.entity.InterestTag;
import com.smartsofa.photo.GifView;
import com.smartsofa.util.MyUtils;

public class NewsFragment extends Fragment {
	
	//定义网络链接地址
	private String url;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private JSONObject json;
	private JSONArray jsonarr;
	private Boolean flag;
	
	//定义加载动画
	GifView detail_loading;
	//定义适配器数据
	private List<Map<String,Object>> mData;
	
	ListView lv_news;
	
	private final static String TAG = "NewsFragment";
	Activity activity;
	String text;
	int channel_id;

	public final static int SET_NEWSLIST = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Bundle args = getArguments();
		text = args != null ? args.getString("text") : "";
		channel_id = args != null ? args.getInt("id", 0) : 0;
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		this.activity = activity;
		super.onAttach(activity);
	}
	/** 此方法意思为fragment是否可见 ,可见时候加载数据 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (isVisibleToUser) {
			if(mData!=null&&mData.size()!=0){
				content_handler.obtainMessage(1).sendToTarget();
			}else{
				Thread get_news_thread=new Thread(new loadNewsThread());
				get_news_thread.start();
			}			
		}else{
			//fragment不可见时不执行操作
		}
		super.setUserVisibleHint(isVisibleToUser);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = LayoutInflater.from(getActivity()).inflate(R.layout.news_fragment, null);	
		detail_loading=(GifView) view.findViewById(R.id.loading_news_list);
		detail_loading.setMovieResource(R.raw.loading);
		lv_news=(ListView) view.findViewById(R.id.lv_newsinfo);
		return view;
	}
	
	class loadNewsThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				
				url=MyUtils.getUrl()+"knowledge_getNewsList?text="+text+"&interest="+InterestTag.convertToString();
				Log.i("url:", url);
				HttpGet request = new HttpGet(url.replaceAll("#", "%23"));																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = content_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			content_handler.sendMessage(msg);
		}
		
	}
	
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {			
			switch (msg.what) {		
			case 1:	
				try {
					if(json.get("msg").equals("推荐")){
						mData=getRecommendData(json);
					}else{
						mData=getData(json);
					}					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				NewsListAdapter adapter=new NewsListAdapter(activity, mData);
				detail_loading.setVisibility(View.GONE);
				lv_news.setAdapter(adapter);
				break;
			case 2:
				detail_loading.setVisibility(View.GONE);
				Toast.makeText(activity, "数据加载失败，请稍后重试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				detail_loading.setVisibility(View.GONE);
				Toast.makeText(activity, "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}		
	};
	
	/**
	 * 将JSONArray转换为适配器数据格式
	 * @throws JSONException 
	 */
	private List<Map<String, Object>> getData(JSONObject json) throws JSONException{
		jsonarr=json.getJSONArray("obj");	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	    for(int i=0;i<jsonarr.length();i++)  
           {  			    	   
               HashMap<String, Object> map = new HashMap<String, Object>();  
              
			   map.put("categoryId", jsonarr.getJSONObject(i).get("categoryId"));
			   map.put("infoTitle", jsonarr.getJSONObject(i).get("infoTitle")); 
               map.put("infoTime", jsonarr.getJSONObject(i).get("infoTime"));
               map.put("infoId", jsonarr.getJSONObject(i).get("infoId"));
               map.put("infoAbstarct", jsonarr.getJSONObject(i).get("infoAbstarct"));
               map.put("infoUrl", jsonarr.getJSONObject(i).get("infoUrl"));
               list.add(map);
           }
	    return list;
	}
	
	/**
	 * 将JSONArray转换为适配器数据格式
	 * @throws JSONException 
	 */
	private List<Map<String, Object>> getRecommendData(JSONObject json) throws JSONException{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		jsonarr=json.getJSONArray("obj").getJSONArray(0);	
	    for(int i=0;i<jsonarr.length();i++)  
           {  			    	   
               HashMap<String, Object> map = new HashMap<String, Object>();  
              
			   map.put("categoryId", jsonarr.getJSONObject(i).get("categoryId"));
			   map.put("infoTitle", jsonarr.getJSONObject(i).get("infoTitle")); 
               map.put("infoTime", jsonarr.getJSONObject(i).get("infoTime"));
               map.put("infoId", jsonarr.getJSONObject(i).get("infoId"));
               map.put("infoAbstarct", jsonarr.getJSONObject(i).get("infoAbstarct"));
               map.put("infoUrl", jsonarr.getJSONObject(i).get("infoUrl"));
               list.add(map);
           }				
	    return list;
	}
/*	private List<Map<String, Object>> getRecommendData(JSONObject json) throws JSONException{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for(int j=0;j<json.getJSONArray("obj").length();j++){
			jsonarr=json.getJSONArray("obj").getJSONArray(j);	
		    for(int i=0;i<jsonarr.length();i++)  
	           {  			    	   
	               HashMap<String, Object> map = new HashMap<String, Object>();  
	              
				   map.put("categoryId", jsonarr.getJSONObject(i).get("categoryId"));
				   map.put("infoTitle", jsonarr.getJSONObject(i).get("infoTitle")); 
	               map.put("infoTime", jsonarr.getJSONObject(i).get("infoTime"));
	               map.put("infoId", jsonarr.getJSONObject(i).get("infoId"));
	               map.put("infoAbstarct", jsonarr.getJSONObject(i).get("infoAbstarct"));
	               map.put("infoUrl", jsonarr.getJSONObject(i).get("infoUrl"));
	               list.add(map);
	           }
		}		
	    return list;
	}*/
	
	

	/* 摧毁视图 */
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		Log.d("onDestroyView", "channel_id = " + channel_id);
	}
	/* 摧毁该Fragment，一般是FragmentActivity 被摧毁的时候伴随着摧毁 */
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "channel_id = " + channel_id);
	}
}